<template>
	<view class="container">
		<uni-nav-bar title="轮播图" fixed statusBar :border="false" leftIcon='back' @clickLeft="goBackPage"></uni-nav-bar>
		<text class="tip">
			Tip：在此设置首页轮播图，您可对图片进行新增、删除、查看操作，最多可上传 9 张
		</text>
		<view class="picker">
			<uni-file-picker v-model='fileData' limit="9" title="最多选择9张图片" @success="successUpload"
				@delete="deleteImg"></uni-file-picker>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import {
		ref
	} from 'vue';

	const fileData = ref([])

	const loadingOptions = {
		loadingOptions: {
			title: '加载中...',
			mask: true
		},
		errorOptions: {
			type: 'toast'
		}
	}

	const goBackPage = () => uni.navigateBack()

	const successUpload = async (e) => {
		const homeSwipper = uniCloud.importObject('home-swipper')
		try {
			const res = await homeSwipper.addData(e?.tempFiles)
			uni.showToast({
				title: '上传成功',
				icon: 'success'
			})
		} catch (err) {
			console.log('错误 ', err.errCode, '：', err.errMsg, 'Json：', err)
		}
		getData({
			customUI: true
		})
	}

	const deleteImg = async (e) => {
		const homeSwipper = uniCloud.importObject('home-swipper')
		try {
			const res = await homeSwipper.deleteData(e.tempFile._id)
			uni.showToast({
				title: '删除成功',
				icon: 'success'
			})
		} catch (err) {
			console.log('错误 ', err.errCode, '：', err.errMsg, 'Json：', err)
		}
		getData({
			customUI: true
		})
	}

	const getData = async (options = loadingOptions) => {
		const homeSwipper = uniCloud.importObject('home-swipper', options)
		try {
			const res = await homeSwipper.getData()
			fileData.value = res?.data?.map(item => ({
				...item?.image,
				_id: item._id
			}))
		} catch (err) {
			console.log('错误 ', err.errCode, '：', err.errMsg, 'Json：', err)
		}
		uni.stopPullDownRefresh()
	}

	onPullDownRefresh(() => getData())
	onLoad(() => {
		getData()
	})
</script>

<style lang="scss" scoped>
	@import url("/styles/common.scss");

	.container {}

	.tip {
		display: block;
		font-size: 14px;
		text-indent: 2em;
		color: #666;
		background-color: var(--background-color);
		box-shadow: inset 0 2px 6px 0 rgba(0, 0, 0, 0.04);
		line-height: 24px;
		padding: 6px 16px;
		border-top: 1px solid #eee;
		border-bottom: 1px solid #eee;

		&-link {
			color: #54a1ff;
			text-decoration: underline;
		}
	}

	.picker {
		margin: var(--margin-vertical);
	}
</style>